#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <string.h>
#include <unistd.h>

class UDPServer
{
public:
    UDPServer(std::string ip, uint16_t port)
        : _ip(ip), _port(port)
    {
    }

    void Init() // 服务器初始化
    {
        // 1. 创建套接字
        _socketId = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketId < 0)
        {
            std::cout << "socket error" << std::endl;
            exit(1);
        }
        // 2. 绑定端口号
        struct sockaddr_in ser_addr;            // 服务器信息
        memset(&ser_addr, 0, sizeof(ser_addr)); // 清零
        ser_addr.sin_family = AF_INET;
        ser_addr.sin_port = htons(_port);
        ser_addr.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());

        if (bind(_socketId, (struct sockaddr *)&ser_addr, sizeof(ser_addr)) < 0)
        {
            std::cout << "bind error" << std::endl;
            exit(1);
        }

        std::cout << ">>>Server Init Success<<<" << std::endl;
    }

    void Start() // 运行服务器
    {
        std::cout << ">>>Server Running<<<" << std::endl;
        char buffer[1024]; // 接收消息缓冲区
        while (1)
        {
            // 1. 接收消息
            struct sockaddr_in cli_addr;      // 接收客户端信息
            socklen_t len = sizeof(cli_addr); // 输入输出型参数
            memset(&cli_addr, 0, sizeof(cli_addr));
            ssize_t s = recvfrom(_socketId, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&cli_addr, &len);
            if (s > 0)
            {
                buffer[s] = '\0';

                if (!strcmp("quit", buffer))
                {
                    sendto(_socketId, buffer, s, 0, (struct sockaddr *)&cli_addr, sizeof(cli_addr)); // 发送给客户端
                    break;
                }

                std::cout << ">>>Server Receive<<<" << std::endl;

                std::cout << '[' << inet_ntoa(cli_addr.sin_addr) << ':' << ntohs(cli_addr.sin_port) << "]#";
                std::cout << buffer << std::endl;
            }
            // 2. 处理消息--此处将单词转大写返回给客户端
            int i = 0;
            while (buffer[i] != '\0')
            {
                buffer[i] = toupper(buffer[i]);
                ++i;
            }

            std::cout << ">>>Server Send<<<" << std::endl;
            std::cout << buffer << std::endl;
            sendto(_socketId, buffer, s, 0, (struct sockaddr *)&cli_addr, sizeof(cli_addr)); // 发送给客户端
        }
    }

    ~UDPServer()
    {
        // 关闭套接字
        std::cout << ">>>Server Closed<<<" << std::endl;
        close(_socketId);
    }

private:
    int _socketId;   // 套接字id
    std::string _ip; // IP地址
    uint16_t _port;  // 端口号
};
